﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NoMiddleman.Core.Domain;
using NoMiddleman.Data;
using NoMiddleman.Facades.DataTransferObjects;

namespace NoMiddleman.Facades.Facades
{
    public class AdvertFacade
    {
        private readonly AdvertRepository advertRepository;

        public AdvertFacade(AdvertRepository advertRepository)
        {
            this.advertRepository = advertRepository;
        }

        public ICollection<AdvertDTO> GetAdverts()
        {
            ICollection<AdvertDTO> coll = new List<AdvertDTO>();
            foreach (var advert in advertRepository.GetAll())
            {
                coll.Add(AdvertFactory.GetAdvertDTO(advert));
            }
            return coll;
        }

        public AdvertDTO AddAdvert(AdvertDTO advertDTO)
        {
            Advert advert = AdvertFactory.GetAdvert(advertDTO);
            
            ClientRepository crepo = new ClientRepository();
            var client = crepo.Get(advertDTO.Client.Id);

            if (client.TryAddAdvert(advert))
            {
                var res = AdvertFactory.GetAdvertDTO(advertRepository.Save(advert));
                crepo.Update(client);
                return res;
            }

            return null;
        }

        public AdvertDTO GetAdvert(int id)
        {
            return AdvertFactory.GetAdvertDTO(advertRepository.Get(id));
        }
    }
}
